package com.shixun.milktea.converter;

import org.springframework.format.Formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateFormatter implements Formatter<Date> {
    /**
     * 日期格式转换器
     *  后台定义前台传递日期字符串的格式要
     *  yyyy-MM-dd
     *  yyyy/MM/dd
     *  yyyy-MM-dd hh:mm:ss.sss
     * @param text
     * @param locale
     * @return
     * @throws ParseException
     */
    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        //定义正则表达式 识别日期格式的字符串
        //正则 [0-9]表示后面的字符有0-9数组组成  yyyy-MM-dd
        String regDate="^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$";
        //yyyy-MM-dd hh:mm:ss
        String regDateTime="^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}\\s[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}$";
        SimpleDateFormat format;
        if(text.trim().matches(regDate)){
            format=new SimpleDateFormat("yyyy-MM-dd");
        }else if(text.trim().matches(regDateTime)){
            format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        }else {
            return null;
        }
        Date date = format.parse(text);
        return date;
    }

    @Override
    public String print(Date object, Locale locale) {
        return null;
    }


    private static boolean isSameDate(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);

        boolean isSameYear = cal1.get(Calendar.YEAR) == cal2
                .get(Calendar.YEAR);
        boolean isSameMonth = isSameYear
                && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
        boolean isSameDate = isSameMonth
                && cal1.get(Calendar.DAY_OF_MONTH) == cal2
                .get(Calendar.DAY_OF_MONTH);

        return isSameDate;
    }



}